var createError = require('http-errors');
var express = require('express');
const bodyParser = require('body-parser')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
require('dotenv').config()

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var adminRouter = require('./routes/admin');

var app = express();
var http = require('http');
var server = http.createServer(app);
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-type,Content-Length,Authorization,Accept,X-Requested-Width");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended:true}))
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/admin', adminRouter);



/**
 * 聊天
 */
const io = require('socket.io')(server);
let map = new Map()
io.on('connection', (socket) => {
  console.log('a user connected');
  /* 监听登录事件 */
  socket.on('login', data => {
    console.log(data.name+'登录'+socket.id);
    map.set(data.name, socket.id)
    socket.name = data.name
  })
  /* 监听私聊事件 */
  socket.on('privateChat', data => {
    /* 找到对应的私聊对象 */
    console.log(data)
    console.log('receiver.id',map.get(data.receiver));
    io.to(map.get(data.receiver)).emit('updateChatMessageList', data);
  });
});
/**
 * 聊天
 */

console.log('************************SERVICE STARTED***********************')
server.listen('3000')
